package com.example.trans.controller;

import com.example.trans.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/register")
    public Boolean register(String userName, String password){
        // 1. 参数校验
        log.info("/user/register接收到参数：userName: {}, password: {}", userName, password);
        if(!StringUtils.hasLength("userName") || !StringUtils.hasLength(password)){
            return false;
        }
        // 2. 开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        // 3. 调用 service
        try{
            Integer result = userInfoService.insertUserInfo(userName, password);
            if(result <= 0){
                return false;
            }
        }catch (Exception e){
            return false;
        }
        // 4. 提交事务
//        dataSourceTransactionManager.commit(transactionStatus);
        // 5. 回滚事务
        dataSourceTransactionManager.rollback(transactionStatus);

        return true;
    }
}
